package web;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.Student;
import service.StudentInfoService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StudentInfoServlet  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("StudentInfoServlet服务器接收到客户端的登录请求");

        //1.接收到查询学生信息请求就将学生信息返回
        //2.创建一个List对象来存放要展示的数据
        List student_list = new ArrayList();
        //获取学生信息
        try {
            ArrayList<Student> students_info = new StudentInfoService().StudentInfoService();
            for(Student std: students_info){
                //3.创建一个map对象，给map中设置内容
                Map<String, Object> map = new HashMap<>();
                map.put("id", std.getId());
                map.put("name", std.getName());
                map.put("gender", std.getGender());
                map.put("birth", std.getDate());
                student_list.add(map);
            }
            //5 map转成json返回给前台
            ObjectMapper om = new ObjectMapper();
            String mapJson = om.writeValueAsString(student_list);
            //6 json数据返回给前台
            resp.getWriter().println(mapJson);
            System.out.println(mapJson);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }
}
